<template>
	<view class="register-container">
		<uv-toast ref="toast"></uv-toast>
		<view class="header">
			<text class="title">商户入驻</text>
			<text class="subtitle">Register Your Store</text>
		</view>

		<scroll-view scroll-y class="form-container">
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="info-circle" size="32" color="#3c9cff"></uv-icon>
					<text>基本信息</text>
				</view>

				<view class="input-group">
					<text class="label required">门店名称</text>
					<uv-input v-model="formData.name" placeholder="请输入门店名称" maxlength="50" />
				</view>

				<view class="input-group">
					<text class="label required">商家名称</text>
					<uv-input v-model="formData.merchantName" placeholder="请输入商家名称" maxlength="50" />
				</view>

				<view class="input-group">
					<text class="label required">登录密码</text>
					<uv-input v-model="formData.password" type="password" placeholder="请设置登录密码" />
				</view>
			</view>

			<!-- 联系方式 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="phone" size="32" color="#3c9cff"></uv-icon>
					<text>联系方式</text>
				</view>

				<view class="input-group">
					<text class="label required">负责人</text>
					<uv-input v-model="formData.director" placeholder="请输入负责人姓名" maxlength="20" :border="false" />
					<text v-if="formErrors.director" class="error-tip">{{ formErrors.director }}</text>
				</view>

				<view class="input-group">
					<text class="label required">联系电话</text>
					<uv-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" type="number"
						:border="false" @input="validatePhone" />
					<text v-if="formErrors.phone" class="error-tip">{{ formErrors.phone }}</text>
				</view>
			</view>

			<!-- 店铺地址 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="map" size="32" color="#3c9cff"></uv-icon>
					<text>店铺地址</text>
				</view>

				<view class="address-picker">
					<text class="address-tip required">请选择店铺位置</text>
					<view class="location-btn" @tap="chooseLocation">
						<view class="btn-content">
							<view class="left">
								<uv-icon name="map-fill" size="40" color="#3c9cff"></uv-icon>
								<text class="btn-text">{{ formData.street || '点击选择店铺位置' }}</text>
							</view>
							<uv-icon name="arrow-right" size="24" color="#909399"></uv-icon>
						</view>
					</view>

					<!-- 地址预览 -->
					<view class="address-preview" v-if="formData.street">
						<view class="preview-item">
							<text class="label">详细地址</text>
							<text class="value">{{ formData.street }}</text>
						</view>
						<view class="preview-item">
							<text class="label">所在地区</text>
							<text class="value">{{ formData.district }}</text>
						</view>
					</view>

					<!-- 地图预览 -->
					<map v-if="formData.latitude && formData.longitude" :latitude="Number(formData.latitude)"
						:longitude="Number(formData.longitude)" :markers="markes" class="map-preview">
					</map>
				</view>
			</view>

			<!-- 店铺信息 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="shop_fill" size="32" color="#3c9cff" custom-prefix="custom-icon"></uv-icon>
					<text>店铺信息</text>
				</view>

				<view class="input-group">
					<text class="label">营业时间</text>
					<uv-input v-model="formData.openingHours" placeholder="例：09:00-22:00" maxlength="20" />
				</view>

				<view class="input-group">
					<text class="label">店铺描述</text>
					<uv-textarea v-model="formData.des" placeholder="请输入店铺描述" maxlength="1000" />
				</view>

				<view class="upload-section">
					<text class="label">店铺图片</text>

					<!-- 上传按钮 -->
					<view class="upload-area" v-if="!formData.image" @tap="afterRead">
						<view class="upload-button">
							<uv-icon name="camera-fill" size="44" color="#3c9cff"></uv-icon>
							<text>上传店铺图片</text>
						</view>
					</view>

					<!-- 图片预览区 -->
					<view class="preview-area" v-else>
						<image class="preview-image" :src="formData.image" mode="aspectFill" />
						<!-- 删除按钮 -->
						<view class="delete-btn" @tap.stop="deletePic">
							<uv-icon name="close" color="#fff" size="20"></uv-icon>
						</view>
						<!-- 重新上传蒙层 -->
						<view class="preview-mask" @tap="afterRead">
							<uv-icon name="reload" size="30" color="#fff"></uv-icon>
							<text>重新上传</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 结算信息 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="money-exchange-settlement" size="32" color="#3c9cff"
						custom-prefix="custom-icon"></uv-icon>
					<text>结算信息</text>
				</view>

				<view class="input-group">
					<text class="label required">开户行</text>
					<uv-input v-model="formData.bankName" placeholder="请输入开户行名称" />
					<text v-if="formErrors.bankName" class="error-tip">{{ formErrors.bankName }}</text>
				</view>

				<view class="input-group">
					<text class="label required">银行账号</text>
					<uv-input v-model="formData.bankAccount" placeholder="请输入银行账号" type="number" />
					<text v-if="formErrors.bankAccount" class="error-tip">{{ formErrors.bankAccount }}</text>
				</view>
			</view>

			<!-- 营业执照上传 -->
			<view class="form-section">
				<view class="section-title">
					<uv-icon name="camera" size="32" color="#3c9cff"></uv-icon>
					<text>证件上传</text>
				</view>

				<view class="upload-section">
					<text class="label required">营业执照</text>

					<!-- 上传按钮 -->
					<view class="upload-area" v-if="!formData.businessLicense" @tap="uploadBusinessLicense">
						<view class="upload-button">
							<uv-icon name="camera-fill" size="44" color="#3c9cff"></uv-icon>
							<text>上传营业执照</text>
						</view>
					</view>

					<!-- 图片预览区 -->
					<view class="preview-area" v-else>
						<image class="preview-image" :src="formData.businessLicense" mode="aspectFill" />
						<!-- 删除按钮 -->
						<view class="delete-btn" @tap.stop="deleteBusinessLicense">
							<uv-icon name="close" color="#fff" size="20"></uv-icon>
						</view>
						<!-- 重新上传蒙层 -->
						<view class="preview-mask" @tap="uploadBusinessLicense">
							<uv-icon name="reload" size="30" color="#fff"></uv-icon>
							<text>重新上传</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部按钮 -->
		<view class="footer">
			<button class="submit-btn" :class="{ 'loading': isSubmitting }" @tap="handleSubmit">提交审核</button>
		</view>
	</view>
</template>

<script>
	import {
		getUserLocation
	} from '@/utils/location.js';
	export default {
		data() {
			return {
				formData: {
					name: '',
					merchantName: '',
					street: '',
					director: '',
					phone: '',
					province: '',
					city: '',
					district: '',
					des: '',
					openingHours: '',
					status: 1,
					latitude: '',
					longitude: '',
					image: '',
					password: '',
					bankName: '',
					bankAccount: '',
					businessLicense: ''
				},
				fileList: [],
				isSubmitting: false,
				formErrors: {
					name: '',
					merchantName: '',
					director: '',
					phone: '',
					address: '',
					password: '',
					bankName: '',
					bankAccount: '',
					businessLicense: ''
				},
				// 地图标记点
				markes: [{
					id: 1,
					latitude: 0,
					longitude: 0,
					height: 30,
					width: 30,
					iconPath: '/static/location.png'
				}],
				// 地图缩放等级 3-20
				scale: 17,
				// 地图中心维度
				centerlongitude: '',
				centerlatitude: '',
				uploadedImage: '', // 记录上传的图片路径
				hasUnsavedImage: false, // 是否有未保存的图片
				uploadedLicense: '', // 记录已上传的营业执照路径
				hasUnsavedLicense: false // 是否有未保存的营业执照
			}
		},

		watch: {
			formData: {
				handler(val) {
					this.validateForm()
				},
				deep: true
			}
		},

		onLoad() {
			this.fetchUserLocation();
		},

		computed: {
			isFormValid() {
				const {
					name,
					merchantName,
					director,
					phone,
					street,
					latitude,
					longitude,
					password
				} = this.formData

				const phoneReg = /^\+?[0-9]{10,15}$/

				return name &&
					merchantName &&
					director &&
					phoneReg.test(phone) &&
					street &&
					latitude &&
					longitude &&
					password.length >= 6
			}
		},

		methods: {
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			async fetchUserLocation() {
				// 获取用户经纬度
				await uni.getLocation({
					geocode: true,
					type: 'gcj02',
					success: (location) => {
						this.centerlatitude = location.latitude;
						this.centerlongitude = location.longitude;
						// 标记地址
						this.markes[0].latitude = location.latitude;
						this.markes[0].longitude = location.longitude;
					},
					fail: (err) => {
						console.log(err);
						this.showToast('获取定位失败，请开启定位，并允许小程序获取定位', 'default', 3000);
					}
				});
			},
			validateForm() {
				let isValid = true
				// 重置错误信息
				Object.keys(this.formErrors).forEach(key => {
					this.formErrors[key] = ''
				})

				// 验证必填字段
				if (!this.formData.name) {
					this.formErrors.name = '请输入门店名称'
					isValid = false
				}

				if (!this.formData.merchantName) {
					this.formErrors.merchantName = '请输入商家名称'
					isValid = false
				}

				if (!this.formData.director) {
					this.formErrors.director = '请输入负责人姓名'
					isValid = false
				}

				// 手机号验证
				if (!this.formData.phone) {
					this.formErrors.phone = '请输入联系电话'
					isValid = false
				} else {
					const phoneReg = /^1[3-9]\d{9}$/
					if (!phoneReg.test(this.formData.phone)) {
						this.formErrors.phone = '请输入正确的手机号码'
						isValid = false
					}
				}

				if (!this.formData.street || !this.formData.latitude || !this.formData.longitude) {
					this.formErrors.address = '请选择店铺位置'
					isValid = false
				}

				if (!this.formData.password) {
					this.formErrors.password = '请输入密码'
					isValid = false
				} else if (this.formData.password.length < 6) {
					this.formErrors.password = '密码长度不能少于6位'
					isValid = false
				}

				// 验证审核信息
				if (!this.formData.bankName) {
					this.formErrors.bankName = '请输入开户行名称'
					isValid = false
				}

				if (!this.formData.bankAccount) {
					this.formErrors.bankAccount = '请输入银行账号'
					isValid = false
				}

				if (!this.formData.businessLicense) {
					this.formErrors.businessLicense = '请上传营业执照'
					isValid = false
				}

				return isValid
			},

			async chooseLocation() {
				try {
					// 先获取用户位置权限
					const {
						error,
						res
					} = await uni.authorize({
						scope: 'scope.userLocation'
					});

					if (error) {
						throw new Error('请允许获取位置权限');
					}

					// 调起地图选点
					const location = await uni.chooseLocation();

					// 更新表单数据
					this.formData.latitude = location.latitude;
					this.formData.longitude = location.longitude;
					this.formData.street = location.name;
					this.formData.district = location.address;

					// 更新地图标记
					this.markes[0].latitude = location.latitude;
					this.markes[0].longitude = location.longitude;

				} catch (error) {
					console.error('选择位置失败', error);
					this.showToast('选择位置失败', 'default', 1000);
				}
			},

			async afterRead() {
				try {
					// 如果之前有未保存的图片，先删除
					if (this.hasUnsavedImage && this.uploadedImage) {
						await this.deleteUnsavedImage();
					}

					const res = await this.$http.urlImgUpload('/auth/merchant/image/upload', {
						name: 'file',
						maxSize: 1024 * 1024 * 5,
						count: 1
					});

					if (res) {
						this.formData.image = res[0];
						this.uploadedImage = res[0]; // 记录新上传的图片路径
						this.hasUnsavedImage = true; // 标记有未保存的图片
						this.showToast('上传成功', 'success', 1000);
					}
				} catch (e) {
					this.showToast('上传失败', 'error', 1000);
				}
			},

			async checkBeforeExit() {
				try {
					if (this.hasUnsavedImage && this.uploadedImage) {

						// 删除未保存的图片
						await this.deleteUnsavedImage();

						// 重置相关状态
						this.formData.image = '';
						this.uploadedImage = '';
						this.hasUnsavedImage = false;
					}
				} catch (error) {
					console.error('清理图片失败', error);
				}
			},

			async deletePic() {
				try {
					if (this.hasUnsavedImage && this.uploadedImage) {
						await this.deleteUnsavedImage();
					}
					this.formData.image = '';
					this.uploadedImage = '';
					this.hasUnsavedImage = false;
				} catch (error) {
					console.error('删除图片失败', error);
				}
			},

			async deleteUnsavedImage() {
				try {
					await this.$http.post('/auth/merchant/image/delete', {
						image: this.uploadedImage
					});
					console.log('已删除未保存的图片');
				} catch (error) {
					console.error('删除图片失败', error);
				}
			},

			async handleSubmit() {
				if (!this.validateForm()) {
					const firstError = Object.values(this.formErrors).find(error => error)
					if (firstError) {
						this.showToast(firstError, 'error')
					}
					return
				}

				this.isSubmitting = true
				try {
					const res = await this.$http.post('/merchant/application/submit', this.formData)
					if (res) {
						this.hasUnsavedLicense = false // 提交成功后重置状态
						this.uploadedLicense = ''
						this.showToast('提交成功', 'success')
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (error) {
					this.showToast(error.msg || '提交失败', 'error')
				} finally {
					this.isSubmitting = false
				}
			},

			// 验证手机号
			validatePhone(value) {
				this.formErrors.phone = ''

				// 清除非数字字符
				const cleanValue = value.replace(/\D/g, '')

				// 限制长度为11位
				if (cleanValue.length > 11) {
					this.formData.phone = cleanValue.slice(0, 11)
					return
				}

				this.formData.phone = cleanValue

				// 如果不是空值则验证格式
				if (cleanValue) {
					// 验证手机号格式
					const phoneReg = /^1[3-9]\d{9}$/
					if (!phoneReg.test(cleanValue)) {
						this.formErrors.phone = '请输入正确的手机号码'
					}
				}
			},

			// 上传营业执照
			async uploadBusinessLicense() {
				try {
					// 如果之前有未保存的照片，先删除
					if (this.hasUnsavedLicense && this.uploadedLicense) {
						await this.deleteUnsavedLicense();
					}

					const res = await this.$http.urlImgUpload('/merchant/application/upload/businessLicense', {
						name: 'file',
						maxSize: 1024 * 1024 * 5,
						count: 1
					})

					if (res) {
						this.formData.businessLicense = res[0]
						this.uploadedLicense = res[0] // 记录新上传的照片路径
						this.hasUnsavedLicense = true // 标记有未保存的照片
						this.showToast('上传成功', 'success')
					}
				} catch (e) {
					this.showToast('上传失败', 'error')
				}
			},

			// 删除营业执照
			async deleteBusinessLicense() {
				try {
					if (this.hasUnsavedLicense && this.uploadedLicense) {
						await this.deleteUnsavedLicense()
					}
					this.formData.businessLicense = ''
					this.uploadedLicense = ''
					this.hasUnsavedLicense = false
				} catch (error) {
					console.error('删除营业执照失败', error)
				}
			},

			// 删除未保存的营业执照
			async deleteUnsavedLicense() {
				try {
					await this.$http.delete(`/merchant/application/del/businessLicense?path=${this.uploadedLicense}`)
				} catch (error) {
					console.error('删除营业执照失败', error)
				}
			}
		},

		// 添加页面生命周期钩子
		onUnload() {
			this.checkBeforeExit()
		},

		// 监听返回按钮
		onBackPress() {
			if (this.hasUnsavedLicense) {
				this.checkBeforeExit()
			}
			return false
		}
	}
</script>

<style lang="scss" scoped>
	@import 'register_merchant.scss';
</style>